<?php
namespace app\platform\controller;
use think\Controller;
use think\Collection;
use app\index\platform\Users;
use app\index\platform\DocDocumentEncrypt as docEncrypt;

class Base extends Controller{
	private $success  = true;
	private $code  = 0;
	private $msg  = '成功';
	private $data = [];

	public function return_succ($data=[]){
		$result=$this->is_params($data);
		return json($result);
	}

	public function return_err($data=[]){
		$this->success=false;
		$this->code=1;
		$this->msg='错误';
		$result=$this->is_params($data);
		return json($result);
	}
	public function is_params($params) {
		if(is_array($params)){
			$flag = true;
			if (array_key_exists('success', $params)) {
				$this->success = $params['success'];
				$flag       = false;
			}
			if (array_key_exists('code', $params)) {
				$this->code = $params['code'];
				$flag       = false;
			}
			if (array_key_exists('msg', $params)) {
				$this->msg = $params['msg'];
				$flag       = false;
			}
			if (array_key_exists('data', $params)) {
				$this->data = $params['data'];
			}else{
				if ($flag) {
					$this->data = $params;
				}
			}
		}else{
			$this->data = $params;
		}
		return ['success' => $this->success,'code' => $this->code,'msg' => $this->msg,'data' => $this->data];
	}

	//文件下载
	public function down($file){

		if (file_exists($file)) {
			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename="'.basename($file).'"');
			header('Expires: 0');
			header('Cache-Control: must-revalidate');
			header('Pragma: public');
			header('Content-Length: ' . filesize($file));
			readfile($file);
			//下载后删除文件
			@unlink($file);
			exit;
		}
	}
	
	/**
	 * 给二维数组中的每个一维数组增加一个新的字段
	 * @param [type] $arrs    数组
	 * @param [type] $filed   新字段
	 * @param [type] $filedValue 新字段值
	 */
	public function addField($arrs,$filed,$filedValue){
		$arr = array();//一个空数组，用来存储增加了字段一维数组
		foreach ($arrs as $k=>$value) {
			$value[$filed] = $filedValue;
			$arr[]=$value;
		}
		return $arr;
	}

	//md5加密
	public function encrypt($password){
		return md5(md5($password));
	}

	/**
	 * 获取用户信息(用于api接口)
	 */
	public function getUser() {
		$token=request()->header("token");

		try {
			$cacheToken=cache($token);
			//判断缓存中是否存在
			if(empty($cacheToken)){
				return false;
			}
		} catch (Exception $e){
			return false;
		}

		$token=base64_decode($token);
		$decryptToken=explode('_',$token);
		//判断token中id加密字符串是否存在
		if(!isset($decryptToken[1]) && empty($decryptToken[1])){
			return false;
		}
		//使用用户id加密字符串
		$idSecretKey=$this->encrypt($decryptToken[0].config('config.custom_secret_key'));
		//$decryptToken[1]为token中id加密字符串
		if($idSecretKey!==$decryptToken[1]){
			return false;
		}
		$where=[
			'id'=>$decryptToken[0]//用户id
		];
		$result=Users::queryUser($where);
		if(!$result){
			return false;
		}
		// return Collection::make($result);
		return $result;
	}

	/**
	 * 判断web页面中获取用户信息
	 */
	public function getWebUser($str) {
		$userID=$this->paramDecrypt($str);
		$result=Users::queryUser(['id'=>$userID]);
		if(!$result){
			return false;
		}
		return $result;
	}

	/**
	 * 判断文档是否加密
	 */
	public function checkDocEncrypt($where) {
		//查询文档是否加密
		$result=docEncrypt::checkDocRecord($where);
		if(!$result){
			return false;
		}
		return $result;
	}

	//生成随机昵称
	public function randomNickName() {
		$nickName = ["东北虎", "龙", "鼠", "鸡", "牛", "狗", "猪", "兔", "羊", "蛇", "马", "猴", "松鼠", "考拉", "骆驼", "蜥蜴", "犀牛", "河马", "斑马", "羚羊", "牦牛", "鸭嘴兽", "鱼", "鲸鱼", "带鱼", "海豹", "海豚", "企鹅", "孔雀", "狼", "鹿", "貂", "狐", "熊", "象", "豹子", "狮子", "熊猫", "疣猪", "驯鹿", "树懒", "猞猁", "麝牛", "穿山甲", "长颈鹿", "食蚁兽", "猩猩", "水獭", "灵猫", "刺猬", "北极狐", "啄木鸟", "鸳鸯", "鹦鹉", "鲣鸟", "松鸡"];
		$index=mt_rand(0,count($nickName));
		return '会说话的'.$nickName[$index];
	}

	//生成随机头象
	public function randomHeadImg() {
		$headImg = [
			"/img/headimg/headimg_01.jpg",
			"/img/headimg/headimg_02.jpg",
			"/img/headimg/headimg_03.jpg",
			"/img/headimg/headimg_04.jpg",
			"/img/headimg/headimg_05.jpg",
			"/img/headimg/headimg_06.jpg"
		];
		$index=mt_rand(0,count($headImg)-1);
		return $headImg[$index];
	}

	//参数加密
	public function paramEncrypt($string){
		//密钥
		$key=config('config.params_secret_key');
		$decrypted = openssl_encrypt($string, "DES-ECB", $key, 0);  
		return $this->strToHex($decrypted);
	}

	//参数解密
	public function paramDecrypt($string){
		//密钥
		$key=config('config.params_secret_key');
		$encrypted = openssl_decrypt($this->hexToStr($string), "DES-ECB", $key, 0); 
		return $encrypted;
	}

	/**
	*字符串转十六进制
	*@pream string $str='abc';
	*/
	public function strToHex($str) {
		$hex = "";
		for ($i = 0;$i < strlen($str);$i++) $hex.= dechex(ord($str[$i]));
		$hex = strtoupper($hex);
		return $hex;
	}

	/**
	*十六进制转字符串
	*@pream string $hex='616263';
	*/
	public function hexToStr($hex) {
		$str = "";
		for ($i = 0;$i < strlen($hex) - 1;$i+= 2) $str.= chr(hexdec($hex[$i] . $hex[$i + 1]));
		return $str;
	}

	//=============== start 参数加密，解密 =================//
	//加密
	public function passport_encrypt($arr) {
		$txt=implode('&',$arr);
		//检查加密字符中是否有 "/"
		$encryptStr=$this->passport_check_slash($txt);
		return urlencode($encryptStr);
	}  
	//解密
	public function passport_decrypt($txt) {
		$key=config('config.params_secret_key');
		$txt = $this->passport_key(base64_decode(urldecode($txt)), $key);
		$tmp = '';
		for($i = 0;$i < strlen($txt); $i++) {
			$md5 = $txt[$i];
			$tmp .= $txt[++$i] ^ $md5;
		}
		$tmpArr=explode('&',$tmp);
		return $tmpArr;
	}
	//解析算法
	public function passport_key($txt, $encrypt_key) {
		$encrypt_key = md5($encrypt_key);
		$ctr = 0;
		$tmp = '';
		for($i = 0; $i < strlen($txt); $i++) {
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
			$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
		}
		return $tmp;
	}
	//检查加密字符中是否有 "/"
	public function passport_check_slash($txt){
		$key=config('config.params_secret_key');
		srand((double)microtime() * 1000000);
		$encrypt_key = md5(rand(0, 32000));
		$ctr = 0;
		$tmp = '';
		for($i = 0;$i < strlen($txt); $i++) {
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
			$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
		}
		$encryptStr=base64_encode($this->passport_key($tmp, $key));
		if (strpos($encryptStr, "/") !== false){
			//斜杠"/"存在
			$encryptStr=$this->passport_check_slash($encryptStr);
		}
		return $encryptStr;
	}
	//=============== end 参数加密，解密 =================//



}
